import router from '@/router'
import { defineStore } from 'pinia'
import { RouteLocationNormalized } from 'vue-router'

export interface ExtendedRoute extends RouteLocationNormalized {
	scrollTop?: number // 添加自定义属性
}

// 定义一个 Pinia 状态管理器，名为 'viewTags'
const useViewTagStore = defineStore('viewTags', {
	state: () => {
		return {
			// 存储多个路由标签的数组
			viewTags: [] as ExtendedRoute[]
		}
	},
	actions: {
		// 将新的路由标签添加到标签列表
		pushViewTags(route: ExtendedRoute) {
			const backPathIndex = this.viewTags.findIndex((item) => item.fullPath == router.options.history.state.back)
			const target = this.viewTags.find((item) => item.fullPath === route.fullPath)
			const hasName = route.name
			if (!target && hasName) {
				if (backPathIndex === -1) {
					this.viewTags.push(route)
				} else {
					this.viewTags.splice(backPathIndex + 1, 0, route)
				}
			}
		},
		// 从标签列表中移除指定的路由标签
		removeViewTags(route: RouteLocationNormalized) {
			const index = this.viewTags.findIndex((item) => item.fullPath === route.fullPath)
			if (index !== -1) {
				this.viewTags.splice(index, 1)
			}
		},
		// 更新指定的路由标签
		updateViewTags(route: ExtendedRoute) {
			const index = this.viewTags.findIndex((item) => item.fullPath === route.fullPath)
			if (index !== -1) {
				this.viewTags[index] = { ...this.viewTags[index], ...route }
			}
		},
		// 更新当前标签的标题
		updateViewTagsTitle(title = '') {
			const nowFullPath = location.hash.substring(1)
			const tag = this.viewTags.find((item) => item.fullPath === nowFullPath)
			if (tag) {
				tag.meta.title = title
			}
		},
		// 清空所有视图标签
		clearViewTags() {
			this.viewTags = []
		}
	}
})

// 导出定义的 store 以供使用
export default useViewTagStore
